import {reqLogin,reqRegister,reqCode,reqUserInfo,reqDelLogin} from '@/api'
const state={
    code:'',
    token:localStorage.getItem("TOKEN"),
    userInfo:{}
}
const actions={
    //登录
    async UserLogin({commit},user){
        let result = await reqLogin(user)
        // console.log('login',result);
        if (result.code == 200) {
            //result.data.token  服务器返回的token值
            commit('USERLOGIN',result.data.token)
            //本地存储
            localStorage.setItem("TOKEN", result.data.token);
            return 'ok'
        }else{
            return Promise.reject(new Error('登录失败'))
        }
    },
    //退出登录
    async LoginOut({commit}){
        let result = await reqDelLogin()
        console.log("退出登录===>",result);
        if(result.code == 200){
            commit('CLEAR')
            return 'ok'
        }else{
            return Promise.reject(new Error('退出登录失败！！!'))
        }
    },
    //注册
    async UserRegister({commit},user){
        let result = await reqRegister(user)
        if(result.code== 200){
            return 'ok'
        }else{
            return Promise.reject(new Error('手机号已被注册 || 注册失败！！！'))
        }
    },
    //验证码
    async UserCode({commit},phone){
        let result = await reqCode(phone);
        if(result.code == 200){
            commit('USERCODE',result.data)

            return 'ok'
        }else{
            return Promise.reject(new Error('验证码发送错误！！！'))
        }
    },
    // 获取用户信息
    async getUserInfo({commit}){
        let result = await reqUserInfo()
        console.log('result',result);
        if(result.code==200){
            console.log('result.data',result.data);
            commit('GETUSERINFO',result.data)
            return 'ok'
        }else{
            return Promise.reject(new Error('获取用户信息失败！！！'))
        }
    }

}
const mutations={
    USERCODE(state,result){
        state.code = result
    },
    USERLOGIN(state,result){
        state.token=result
    },
    GETUSERINFO(state,result){
        state.userInfo=result
    },
    //退出登录 将token等字段取消
    CLEAR(state){
        state.token = ''
        state.userInfo = {}
        localStorage.removeItem('TOKEN')
    }
}
const getters={}
export default{
    state,
    actions,
    mutations,
    getters
}